package com.eduplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eduplatform.common.Result;
import com.eduplatform.common.UserContext;
import com.eduplatform.dto.ExamDTO;
import com.eduplatform.dto.ExamPaperDTO;
import com.eduplatform.dto.ExamAnswerDTO;
import com.eduplatform.service.ExamPaperService;
import com.eduplatform.service.ExamService;
import com.eduplatform.service.ExamAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考试控制器
 */
@RestController
@RequestMapping("/api/exams")
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamPaperService examPaperService;

    @Autowired
    private ExamAnswerService examAnswerService;

    @Autowired
    private UserContext userContext;

    /**
     * 分页查询考试列表
     */
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long subjectId,
            @RequestParam(required = false) Integer educationLevel,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long schoolId,
            @RequestParam(required = false) String keyword) {
        IPage<ExamDTO> pageResult = examService.pageExams(page, size, subjectId, educationLevel,
                status, schoolId, keyword);

        Map<String, Object> data = new HashMap<>();
        data.put("total", pageResult.getTotal());
        data.put("pages", pageResult.getPages());
        data.put("current", pageResult.getCurrent());
        data.put("records", pageResult.getRecords());

        return Result.success(data);
    }

    /**
     * 获取考试详情
     */
    @GetMapping("/{id}")
    public Result getDetail(@PathVariable Long id) {
        ExamDTO exam = examService.getExamDetail(id);
        if (exam == null) {
            return Result.error("考试不存在");
        }
        return Result.success(exam);
    }

    /**
     * 添加考试
     */
    @PostMapping("/add")
    public Result add(@RequestBody @Valid ExamDTO examDTO) {
        Long currentUserId = userContext.getCurrentUserId();
        if (currentUserId == null) {
            return Result.error("用户未登录");
        }
        examDTO.setCreatorId(currentUserId);
        boolean result = examService.addExam(examDTO);
        return result ? Result.success() : Result.error("添加考试失败");
    }

    /**
     * 更新考试
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Valid ExamDTO examDTO) {
        if (examDTO.getId() == null) {
            return Result.error("考试ID不能为空");
        }

        boolean result = examService.updateExam(examDTO);
        return result ? Result.success() : Result.error("更新考试失败");
    }

    /**
     * 删除考试
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        boolean result = examService.deleteExam(id);
        return result ? Result.success() : Result.error("删除考试失败");
    }

    /**
     * 更新考试状态
     */
    @PostMapping("/update-status")
    public Result updateStatus() {
        boolean result = examService.updateExamStatus();
        return result ? Result.success() : Result.error("更新考试状态失败");
    }

    /**
     * 系统自动更新考试状态
     */
    @PostMapping("/status/update")
    public Result systemUpdateStatus() {
        boolean result = examService.updateExamStatus();
        return result ? Result.success() : Result.error("自动更新考试状态失败");
    }

    /**
     * 获取考试结果列表
     */
    @GetMapping("/results")
    public Result getResults(@RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "examId", required = false) Long examId,
            @RequestParam(value = "subjectId", required = false) Long subjectId,
            @RequestParam(value = "educationLevel", required = false) Integer educationLevel,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "studentName", required = false) String studentName) {
        IPage<ExamPaperDTO> pageResult = examPaperService.pageExamPapers(page, size, examId, subjectId,
                educationLevel, schoolId, studentName);

        Map<String, Object> data = new HashMap<>();
        data.put("items", pageResult.getRecords());
        data.put("total", pageResult.getTotal());

        return Result.success(data);
    }

    /**
     * 获取考试结果详情
     */
    @GetMapping("/results/{id}")
    public Result getResultDetail(@PathVariable Long id) {
        // 获取考试答卷详情
        ExamPaperDTO examPaperDTO = examPaperService.getExamPaperDetail(id);
        if (examPaperDTO == null) {
            return Result.error("考试答卷不存在");
        }

        // 获取答题记录列表
        List<ExamAnswerDTO> answers = examAnswerService.getExamAnswersByPaperId(id);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("examPaper", examPaperDTO);
        resultMap.put("answers", answers);

        return Result.success(resultMap);
    }
}